<?php
namespace control;

/*
*销售预测类
*/

class saleForecastClass extends adIndexClass
{
    private const page = 'saleForecast';
    private const table = 'sale_forecast';
    private const tableMx = 'sale_forecast_detail';
    private const title = '销售预测';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title' => [
                        'name'  => "标题",
                        'width' => 270,
                    ],
                    'tags'  => [
                        'name'  => "单据标签",
                        'width' => 200,
                    ],
                    'demandDate'         => [
                        'name'  => '需求日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stid'          => [
                        'name'  => '制单人',
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "标题"   => text(array("name" => "title")),
                    '制单人' => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                ],
                [
                    '单据日期'  => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "
                        <span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= " <span onclick=\"layer('orderTag','batchAddTags',{'table':'".self::table."','title':'".self::title."'})\" class='spanButton'>批量打标签</span>\n
                        ";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
            "title" => $this->post('title'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "stid" => $this->post('stid'),
            'coid' => self::$coid,
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print' => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track'=> array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=销售预测单&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认' || !$isEdit) {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "tags":
                        $tags =orderTagClass::getTagName($array['id']);
                        $row[] = $tags;
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            "name" => "保存为草稿",
            "type" => "点击事件",
            "title" => "保存为草稿",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')",
            'style' => 'li-btn-blue-bg',
        ];
        $tr[] = ['', '产品编码', '产品名称', '规格型号', '单位', '数量', '备注'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        $total_num = 0;
        foreach ($result['array'] as $k=>$array) {
            $material = query('material', " id = '$array[materialId]'");
            $select      = select(['name' => 'unit[]', 'option' => inventoryBalanceClass::materialUnit($array['materialId']), 'value' => $array['unit']]);
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])),
                $material['code'],
                $material['name'],
                $material['model'],
                $select,
                text(array('name' => 'num[]', 'type' => 'text', 'blur' => 'calculateTotal', 'other' => self::digitalFiltering('numPrecision'), 'value' => $array['num']?self::lostZero($array['num'],'numPrecision'):'')),
                text(array('name' => 'mxText[]', 'value' => $array['text'])),
            ];
            $total_num += $array['num'];
        }
        $total = [
            5 => "<span id='total_num'>".self::lostZero($total_num,'numPrecision')."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $mxButton = <<<efo
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=saleForecastEditForm]').serialize())">选择产品</span>
efo;
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must ."标题：" => text(["name" => "title", 'class' => 'text', "value" => $info['title']]),
                    must ."需求日期：" => text(["name" => "demandDate", 'class' => 'text', 'laydate' => [], "value" => $info['demandDate']]),
                    must . "单据日期：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ],
                [
                    "备注：" => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '需求明细',
            'button' => $mxButton,
            'html' => $list,
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, '销售预测', self::page, self::page . 'EditForm')
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $cla = self::page;
        $data['html'] .= <<<efo
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}
//计算总数量
function calculateTotal(){
    let table = $('.editList')
    let num = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
</script>

efo;
        //返回
        return $this->tab($data);
    }


    public function editEdit()
    {
        //附件
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $materialIdArr = $this->post('materialId');
        $numArr = $this->post('num');
        $unitArr = $this->post('unit');
        $mxTextArr = $this->post('mxText');

        $field = [
            'title' => $this->post('title'),
            'demandDate' => $this->post('demandDate'),
            'recordDate' => $this->post('recordDate'),
            'text' => $this->post('text'),
        ];
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此销售预测已确认，不能修改';
        } else {
            $json['warn'] = '';
            if (empty($json['warn'])) {
                $this->startTrans();
                $isPass = true;//事务通过标志
                if (!$info['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page,[
                        'prefix' => 'XSYC' . date('Ymd',strtotime($field['recordDate'])),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => " and coid = '".self::$coid."'",
                    ],$field);
                    $field = array_merge($field, [
                        'id' => $id,
                        'orderNo' => $userNo,
                        'state' => '草稿',
                        'coid' => self::$coid,
                        'stid' => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where,
                    ]);
                }

                //添加或更新明细
                if (is_array($mxIdArr)) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx = query(self::tableMx, "id = '$nid'");
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::tableMx,
                                "field" => [
                                    'materialId' => $materialIdArr[$k],
                                    'num' => self::formattingFigure($numArr[$k],'numPrecision'),
                                    'unit' => $unitArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],
                                "where" => " id = '$nid'",
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'materialId' => $materialIdArr[$k],
                                    'num' => self::formattingFigure($numArr[$k],'numPrecision'),
                                    'unit' => $unitArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    $warn = update(array(
                        'table' => 'file',
                        'field' => ['targetId' => $id],
                        'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                    ));
                    if ($warn != '更新成功') {
                        $json['warn'] = $warn;
                        $isPass = false;
                    }
                }
                if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                    $this->commitTrans();
                    delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                    if ($json['warn'] =='新增成功'){
                        self::insertOperateLog($id,self::title,"新建");
                    }
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * @return bool|string
     */
    public function addMx($hidden = '')
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => $hidden .
                hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }


    public function js()
    {
        return <<<efo
<script>
$(function (){
    $(".no-choose").parent().parent().css('color','#d7d7d7');
    $(".no-choose").parent().parent().attr('title','不是当前账套的产品，不可选择');
})
</script>
efo;
    }


    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        $id = $this->post('id');//销售预测ID
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择产品';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material = query('material', "id = '$mxId'");
                $select       = select(['name' => 'unit[]', 'option' => inventoryBalanceClass::materialUnit($material['id']),'value'=>$material['unit']]);
                $suiji = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $mxId)),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $select,
                    text(array('name' => 'num[]', 'type' => 'text', 'blur' => 'calculateTotal', 'other' => self::digitalFiltering('numPrecision'), 'value' => '')),
                    text(array('name' => 'mxText[]', 'value' => '')),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $isClose = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    "提示：" => "是否确认" . ($isClose == 1 ? '关闭' : '开启') . "此订单？",
                ),
            ), 'hidden' => hidden(array('name' => 'type', 'value' => $isClose)),
        ));
        //返回
        return $this->layer(array("title" => "订单状态", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $isClose = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } else {
            $field = [
                'isClose' => $isClose,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $type = $isClose == 1 ? '关闭' : '开启';
                foreach ($idArr as $id) {
                    self::insertOperateLog($id,self::title,$type);
                }
                //添加日志
                $text = $this->control['name'] . $type . "了" . self::title . "， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $type . '成功';
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],

                    ];
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            //按钮
            $button[] = [
                "name" => "打印",
                "type" => "点击事件",
                "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
            ];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "复核",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "cancel") && $info['state'] != '草稿' && !$info['isClose']) {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "edit") && $info['state'] == '已确认') {
                //按钮
                $isClose = $info['isClose'] == 1 ? 0 : 1;
                $name = $info['isClose'] == 1 ? '开启' : '关闭';
                $button[] = [
                    "name" => $name,
                    "type" => "点击事件",
                    "fun" => "layer('" . self::page . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$isClose}'})",
                ];
            }

            $button[] = [
                "name" => "单据追踪",
                "type" => "顶部页卡",
                "title" => "单据追踪",
                "url" => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=销售预测单&id=" . $info['id'],
            ];
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);

            $tr[] = ['产品编码', '产品名称', '规格型号', '单位', '数量', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $total_num = 0;
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $tr[] = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    self::lostZero($array['num'],'numPrecision'),
                    $array['text'],
                ];
                $total_num += $array['num'];
            }
            $total_tr = [
                4 => self::lostZero($total_num, 'numPrecision'),
            ];
            $tags =orderTagClass::getTagName($info['id']);
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "标题" => $info['title'],
                        "需求日期" => $info['demandDate'],
                        "单据日期" => $info['recordDate'],
                        "单据标签" => $tags,
                    ),
                    array(
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '销售明细',
                'html' => $this->listTable(array('tr' => $tr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '销售预测')
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time,
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此销售预测';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此销售预测不是待确认状态，不能确认';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            /*//生成产品需求单
			$bool = $this->product_demands($info['id']);
			if ($bool !==true){
			    $json['warn'] = $bool;
            }
            //生成外购需求单
            $bool = $this->purchase_demands($info['id']);
            if ($bool !==true){
                $json['warn'] = $bool;
            }*/
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * 生成外购需求单
     */
    private function purchase_demands($id): bool|string
    {
        $all = find(array(
            'table'=>"sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"a.*,c.unit",
            'where'=>"b.id = '$id' and c.source = '采购' order by a.list desc"
        ));
        foreach ($all['array'] as $array){
            $lastSupplier = find(array(
                'table' => 'purchase_order as a join purchase_order_detail as b on a.id = b.orderId',
                "single" => "b.materialId = '$array[materialId]' and a.state = '已确认' order by list desc",
                'field' => "supplierId"
            ));
            $warn = static::insert(array(
                'table'=>'product_demands',
                'field'=>[
                    'id'=>suiji(),
                    'coid'=>self::$coid,
                    'sourceType'=>'销售订单',
                    'sourceTable'=>'sale_order',
                    'sourceId'=>$array['orderId'],
                    'sourceMxId'=>$array['id'],
                    'materialId'=>$array['materialId'],
                    'num'=>$array['num'],
                    'unit'=>$array['unit'],
                    'supplierId'=>$lastSupplier['supplierId']??''
                ]
            ));
            if ($warn !='新增成功'){
                return '生成产品需求计划失败';
            }
        }
        return true;
    }
    /**
     * 生成产品需求单
     */
    private function product_demands($id): bool|string
    {
        $all = find(array(
            'table'=>"sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"a.*,c.unit",
            'where'=>"b.id = '$id' and c.source = '自制' order by a.list desc"
        ));
        foreach ($all['array'] as $array){

            $warn = static::insert(array(
                'table'=>'product_demands',
                'field'=>[
                    'id'=>suiji(),
                    'coid'=>self::$coid,
                    'sourceTable'=>'sale_order',
                    'sourceId'=>$array['orderId'],
                    'sourceMxId'=>$array['id'],
                    'materialId'=>$array['materialId'],
                    'num'=>$array['num'],
                    'unit'=>$array['unit'],

                ]
            ));
            if ($warn !='新增成功'){
                return '生成产品需求计划失败';
            }
        }
        return true;
    }


    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此销售预测';
        } elseif ($info['state'] == '草稿') {
            $json['warn'] = '此销售预测是草稿状态，无需撤回';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                self::insertOperateLog($info['id'],self::title,"撤回");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            'title' => '标题',
            'demandDate' => '需求日期',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'title' => 'required',
            'demandDate' => 'required|date',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        $result = find(array('table' => self::tableMx, 'field' => 'id,materialId,unit,num', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善需求明细";
        }
        if(static::is_null_array(array_column($result['array'],'materialId'))){
            return "需求明细中【产品】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'unit'))){
            return "需求明细中【单位】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'num'),false)){
            return "需求明细中【数量】不能为空，且必须大于0";
        }
        return true;
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此销售预测';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此销售预测不是草稿状态，不能提交';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此销售预测，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此销售预测？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此销售预测？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    fileClass::deleteFile($id);
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


    /**
     * 打印
     */
    public function printPage(): string
    {
        $isHiddenPrice = $this->get('price') == 'hidden';
        $info = query(self::table, " id = '{$this->get('id')}'");
        $company = query('company', "coid = '" . self::$coid . "'");//公司名称
        $goodsHtml = '';
        //二维码
        $url = root . 'pay/wxpay/wxScanPng.php?url=' . urlencode("source=sale_forecast&id=" . $info['id']);
        $infoMx = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        $totalNum = $totalMoney = $totalTaxMoney = 0;
        foreach ($infoMx['array'] as $index => $array) {
            $material = query('material', "id = '$array[materialId]'");
            $goodsHtml .= "
                             <tr class='have_border'>
                               <td>" . ($index + 1) . "</td>
                               <td>{$material['code']}</td>
                               <td>{$material['name']}</td>
                               <td>{$material['model']}</td>
                               <td>{$material['unit']}</td>
                               <td>".self::lostZero($array['num'],'numPrecision')."</td>
                               <td>{$array['unit']}</td>
                               <td>{$array['text']}</td>
                             </tr>
                            ";
            $totalNum += $array['num'];
        }
        $info['recordDate'] = date('Y/m/d', strtotime($info['recordDate']));
        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold'>{$company['name']}</div>
                      <div class='printSubTitle'>销售预测</div>
                 </div>
                 <div class='table-top-title'><ul><li>标题：{$info['title']}</li><li>单据日期：{$info['recordDate']}</li><li>预测单号：{$info['orderNo']}</li></ul></div>
              <table class='printTable'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border'>
                   <td>序号</td>
                   <td>产品编码</td>
                   <td>产品名称</td>
                   <td>规格型号</td>
                   <td>单位</td>
                   <td>数量</td>
                   <td>单位</td>
                   <td>备注</td>
                </tr>
                {$goodsHtml}
                 <tr class='have_border'>
                    <td>合计</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>{$totalNum}</td>
                    <td></td>
                    <td></td>
                </tr>

                 <tr class='have_border'>
                    <td colspan='13'>
                         <div>
                               <img alt='二维码' style='width: 100px;vertical-align: top' src='$url'>
                               <div class='footer-ul-parent'>
                               <ul class='footer-ul'>
                                   <li>打印时间：" . date('Y/m/d H:i') . "</li>
                                   <li>制单人：" . self::findStaff($info['stid']) . "</li>
                                   <li>复核人：" . self::findStaff($info['checkId']) . "</li>
                               </ul>
                               </div>
                         </div>
                    </td>
                </tr>
               </tbody>
              </table>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$divHtml}
                    </div>
                  <style>
                  .footer-ul-parent{float: right;margin-right: 10px}
                  .footer-ul li{margin-top: 10px}
                  .table-top-title{
                    height: 30px;
                    line-height: 30px;
                    font-size: 14px;
                    margin-top: 20px;
                  }
                  .table-top-title>ul>li{float: left;width: 250px;}
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html, 'landscape', ['hidenPrice' => true]);
    }
}
